package util;

import java.io.UnsupportedEncodingException;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

public class ConvertUtil {

	/**
	 * Object转String
	 * 
	 * @param o
	 * @return
	 */
	public static String strOf(Object o) {
		return o != null ? o.toString() : "";
	}

	/**
	 * Object转Integer
	 * 
	 * @param o
	 * @return
	 */
	public static Integer integerOf(Object o) {
		try {
			return Integer.valueOf(o.toString());
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * Object转int
	 * 
	 * @param o
	 * @return
	 */
	public static int intOf(Object o) {
		try {
			return Integer.valueOf(o.toString());
		} catch (Exception e) {
			return 0;
		}
	}

	/**
	 * Object转ling
	 * 
	 * @param o
	 * @return
	 */
	public static long longOf(Object o) {
		try {
			return Long.valueOf(o.toString());
		} catch (Exception e) {
			return 0;
		}
	}

	/**
	 * Object转double
	 * 
	 * @param o
	 * @return
	 */
	public static double doubleOf(Object o) {
		try {
			return Double.valueOf(o.toString());
		} catch (Exception e) {
			return 0;
		}
	}

	/**
	 * Object转double
	 * 
	 * @param o
	 * @return
	 */
	public static Double dDoubleOf(Object o) {
		try {
			return Double.valueOf(o.toString());
		} catch (Exception e) {
			return null;
		}
	}

	public static float floatOf(Object o) {
		try {
			return Float.valueOf(o.toString());
		} catch (Exception e) {
			return 0F;
		}

	}

	public static boolean boolOf(Object o) {
		try {
			return o.toString().equals("1") || o.toString().equals("true");
		} catch (Exception e) {
			return false;
		}
	}

	public static Boolean booleanOf(Object o) {
		try {
			return o.toString().equals("1") || o.toString().equals("true");
		} catch (Exception e) {
			return null;
		}
	}

	public static String numberFormat(String s) {
		String result = s;
		try {
			result = NumberFormat.getInstance().format(s);
		} catch (Exception e) {
		}
		return StringUtils.removeEnd(result, ".0");
	}

	/**
	 * ValueContainerMap转HashMap
	 * 
	 * @param o
	 * @return HashMap result
	 */
	public static Map<String, Object> convertHashMap(Map<String, Object> o) {
		Map<String, Object> result = new HashMap<String, Object>();
		for (Object key : o.keySet()) {
			result.put(strOf(key), o.get(key));
		}
		return result;
	}

	public static String doubleToString(double d) {
		String value = String.valueOf(d);
		String last = value.substring(value.indexOf("."), value.length());
		if (".0".equals(last)) {
			value = value.replace(last, "");
		}
		return value;
	}

	/**
	 * 将字符串转换成GBK格式
	 * 
	 * @param sIn
	 * @return
	 */
	public static String parseGbk(String sIn) {
		if (StringUtils.isBlank(sIn)) {
			return sIn;
		}

		try {
			return new String(sIn.getBytes("GBK"), "ISO-8859-1");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return sIn;
	}

	public static String convertSqlIds(String... ids) {
		StringBuilder builder = new StringBuilder();
		for (String str : ids) {
			builder.append(str).append(",");
		}
		return convertSqlIds(StringUtils.removeEnd(builder.toString(), ","));
	}

	public static String convertSqlIds(List<String> ids) {
		StringBuilder builder = new StringBuilder();
		for (String str : ids) {
			builder.append(str).append(",");
		}
		return convertSqlIds(StringUtils.removeEnd(builder.toString(), ","));
	}

	/**
	 * 将传入的字符串转换SQL的形式
	 * 
	 * @param ids
	 *            1;2;3
	 * @param separator
	 *            ;
	 * @return '1','2','3'
	 */
	public static String convertSqlIds(String ids, String separator) {
		if (StringUtils.isBlank(ids)) {
			return "'null'";
		} else {
			StringBuilder builder = new StringBuilder();
			String[] idsArr = StringUtils.split(ids, separator);
			for (int i = 0; i < idsArr.length; i++) {
				builder.append("'").append(idsArr[i]).append("'");
				if (i < idsArr.length - 1) {
					builder.append(",");
				}
			}
			return builder.toString();
		}
	}

	/**
	 * 将传入的字符串转换SQL的形式
	 * 
	 * @param ids
	 *            1,2,3
	 * @return '1','2','3'
	 */
	public static String convertSqlIds(String ids) {
		return convertSqlIds(ids, ",");
	}

	/**
	 * 拼凑in形式的SQL条件
	 * 
	 * @param alias
	 *            a.xh
	 * @param idList
	 *            [1,2,3...1001] size:1001
	 * 
	 * @return (a.xh in ('1', '2' ... '500') or a.xh in ('501', '502' ... '1000') or a.xh in ('1001'))
	 */
	public static String buildSqlCondition(String alias, List<String> idList) {
		if (CollectionUtils.isEmpty(idList)) {
			return "";
		}

		StringBuilder condition = new StringBuilder("(");
		int size = idList.size();
		int p = (int) Math.ceil((double) idList.size() / 500);

		for (int i = 0; i < p; i++) {
			if (i != 0) {
				condition.append(" or ");
			}
			condition.append(alias + " in (");
			for (int j = i * 500; j < i * 500 + 500; j++) {
				condition.append("'" + idList.get(j) + "'");
				if (j + 1 >= size) {
					break;
				} else {
					condition.append(",");
				}
			}
			condition.append(")");
		}
		condition.append(")");
		return condition.toString().replace(",)", ")");
	}

	/**
	 * 模板解析
	 * 
	 * @param tempalte
	 *            {{tableName}}.xh=1
	 * @param parameters
	 *            { tableName:T_XJGL_XSXX_XSJCXX }
	 * @return T_XJGL_XSXX_XSJCXX.xh=1
	 */
	public static String parseTemplate(String tempalte, Map<String, String> parameters) {
		Pattern p = Pattern.compile("(\\{\\{([a-zA-Z0-9_]+)\\}\\})");
		Matcher m = p.matcher(tempalte);
		StringBuffer stringBuffer = new StringBuffer();
		while (m.find()) {
			String key = m.group(2);
			String value = null;
			if (parameters.containsKey(key)) {
				value = parameters.get(key);
			}
			value = (value == null) ? "" : value;
			m.appendReplacement(stringBuffer, value);
		}
		m.appendTail(stringBuffer);
		return stringBuffer.toString();
	}

	public static boolean isInteger(String str) {
		Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
		return pattern.matcher(str).matches();
	}

	/**
	 * 参数字符串转MAP对象
	 */
	public static Map<String, String> getParamsMap(String paramStr) {
		Map<String, String> paramsMap = new HashMap<String, String>();
		if (paramStr != null && paramStr.length() > 0) {
			int ampersandIndex, lastAmpersandIndex = 0;
			String subStr, param, value;
			String[] paramPair;
			do {
				ampersandIndex = paramStr.indexOf('&', lastAmpersandIndex) + 1;
				if (ampersandIndex > 0) {
					subStr = paramStr.substring(lastAmpersandIndex, ampersandIndex - 1);
					lastAmpersandIndex = ampersandIndex;
				} else {
					subStr = paramStr.substring(lastAmpersandIndex);
				}
				paramPair = subStr.split("=");
				param = paramPair[0];
				value = paramPair.length == 1 ? "" : paramPair[1];
				paramsMap.put(param, value);
			} while (ampersandIndex > 0);
		}
		return paramsMap;
	}

	public static String delHTMLTag(String htmlStr) {
		if (StringUtils.isBlank(htmlStr)) {
			return "";
		}
		String regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>"; // 定义script的正则表达式
		String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; // 定义style的正则表达式
		String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式

		Pattern p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
		Matcher m_script = p_script.matcher(htmlStr);
		htmlStr = m_script.replaceAll(""); // 过滤script标签

		Pattern p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
		Matcher m_style = p_style.matcher(htmlStr);
		htmlStr = m_style.replaceAll(""); // 过滤style标签

		Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
		Matcher m_html = p_html.matcher(htmlStr);
		htmlStr = m_html.replaceAll(""); // 过滤html标签
		htmlStr = htmlStr.trim();
		htmlStr = htmlStr.replace("&nbsp;", "");
		return htmlStr; // 返回文本字符串
	}
}
